﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BiliBiliCSharpStudy.old {

    /**
     * 用接口替代“委托”
     */
    class DelegateDemo5InsteadByInterface {
        public static void Demo() {
            Test1();
        }

        public static void Test1() {
            WrapFactory2 wrapFactory = new WrapFactory2();

            IProductFactory1 pizzaFactory = new PizzaFactory1();
            IProductFactory1 toyCarFactory = new ToyCarFactory1();

            Logger1 logger = new Logger1();
            Action<Product1> log = new Action<Product1>(logger.Log);

            Box1 box1 = wrapFactory.WrapProduct(pizzaFactory, log);
            Box1 box2 = wrapFactory.WrapProduct(toyCarFactory, log);

            Console.WriteLine(box1.Product.Name);
            Console.WriteLine(box2.Product.Name);
        }
    }

    interface IProductFactory1 {
        // Product1 定义在 DelegateDemo3.cs 中
        Product1 Make();
    }

    class PizzaFactory1 : IProductFactory1 {
        public Product1 Make() {
            Product1 product1 = new Product1();
            product1.Name = "Pizza";
            product1.Price = 12;
            return product1;
        }
    }

    class ToyCarFactory1 : IProductFactory1 {
        public Product1 Make() {
            Product1 product1 = new Product1() { Name = "Toy Car", Price = 100 };
            return product1;
        }
    }

    class WrapFactory2 {
        /**
         * Reuse, 重复使用，也叫“复用”。代码的复用不但可以提高工作效率，
         * 还可以减少bug的引入。
         * 良好的复用结构是所有优秀软件所共同追求的目标之一。
         */
        public Box1 WrapProduct(IProductFactory1 prodFactory, Action<Product1> logCallback) {
            Box1 box = new Box1();
            Product1 product1 = prodFactory.Make();
            box.Product = product1;
            if (product1.Price >= 50) {
                logCallback(product1);
            }
            return box;
        }
    }
}
